import tkinter as tk
from tkinter import messagebox
import math

# 定义全局变量
quaternion_str = "{ 0, 0, 0, 1 }"

def calculate_quaternion():
    try:
        # 获取输入的角度，并将其转换为弧度
        yaw = math.radians(float(yaw_entry.get()))
        pitch = math.radians(float(pitch_entry.get()))
        roll = math.radians(float(roll_entry.get()))
    except ValueError:
        messagebox.showerror("Error", "Please enter a valid value")
        return
    
    # 计算半角三角函数值
    cy = math.cos(yaw / 2)
    sy = math.sin(yaw / 2)
    cp = math.cos(pitch / 2)
    sp = math.sin(pitch / 2)
    cr = math.cos(roll / 2)
    sr = math.sin(roll / 2)
    
    # 构造四元数
    x = cr * cp * sy - sr * sp * cy
    y = cr * sp * cy + sr * cp * sy
    z = sr * cp * cy - cr * sp * sy
    w = cr * cp * cy + sr * sp * sy

    # 去除浮点数小数部分的尾部无效0和无效小数点，再格式化四元数的字符串表示
    x = round(x, 3)
    y = round(y, 3)
    z = round(z, 3)
    w = round(w, 3)

    global quaternion_str  # 声明为全局变量
    # 格式化四元数字符串
    quaternion_str = "{ "+'{:g}' . format (x)+", "+'{:g}' . format (y)+", "+'{:g}' . format (z)+", "+'{:g}' . format (w)+" }"
    
    # 显示结果
    messagebox.showinfo("Result", quaternion_str)

def copy_to_clipboard():
    global quaternion_str  # 使用全局变量
    root.clipboard_clear()    # 清除剪贴
    root.clipboard_append(quaternion_str)  # 将四元数添加到剪贴板
    messagebox.showinfo("Done", "Copy To Clipboard")

# 创建Tkinter窗口
root = tk.Tk()
root.title("linqiQQ2433268479_Quaternion Calculator For WME")

# 旋转角度输入
yaw_label = tk.Label(root, text="Yaw (Axis X):")
yaw_label.pack(side=tk.LEFT)
yaw_entry = tk.Entry(root)
yaw_entry.pack(side=tk.LEFT)

pitch_label = tk.Label(root, text="Pitch (Axis Y):")
pitch_label.pack(side=tk.LEFT)
pitch_entry = tk.Entry(root)
pitch_entry.pack(side=tk.LEFT)

roll_label = tk.Label(root, text="Roll (Axis Z):")
roll_label.pack(side=tk.LEFT)
roll_entry = tk.Entry(root)
roll_entry.pack(side=tk.LEFT)

# 计算按钮
calc_button = tk.Button(root, text="Calculate Quaternion", command=calculate_quaternion)
calc_button.pack(side=tk.LEFT)

# 复制到剪贴板按钮
copy_button = tk.Button(root, text="Copy To Clipboard", command=copy_to_clipboard)
copy_button.pack(side=tk.LEFT)

# 运行Tkinter事件循环
root.mainloop()

